package com.jstyle.beatecg.activity;

import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.adapter.HistoryDetailAdapter;
import com.jstyle.beatecg.adapter.SportViewPagerAdapter;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.daoManager.PathRecordDaoManager;
import com.jstyle.beatecg.model.Mylocation;
import com.jstyle.beatecg.model.PathRecord;
import com.jstyle.beatecg.util.Util;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.model.ComboLineColumnChartData;
public class HistoryActivity extends AppCompatActivity implements AMap.OnMapLoadedListener,OnMapReadyCallback {

    @BindView(R.id.bt_signin_back)
    ImageView btSigninBack;
    @BindView(R.id.recyclerView_history_detail)
    RecyclerView recyclerViewHistoryDetail;

    @BindView(R.id.map)
    MapView map;
    @BindView(R.id.scrollView_history_detail)
    ScrollView scrollViewHistoryDetail;
    @BindView(R.id.tv_history_type)
    TextView tvHistoryType;
    @BindView(R.id.viewPager_history)
    ViewPager viewPagerHistory;
    @BindView(R.id.rg_history)
    RadioGroup rgHistory;
    private ComboLineColumnChartData data;
    private int numberOfLines = 1;
    private int maxNumberOfLines = 4;
    private int numberOfPoints = 24;
    private float[][] randomNumbersTab = new float[maxNumberOfLines][numberOfPoints];
    private AMap mAMap;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;

    private PathRecord pathRecord;
    private List<LatLng> mOriginLatLngList;
    private Polyline mOriginPolyline;
    private Marker mOriginStartMarker;
    private Marker mOriginEndMarker;
    private Marker mOriginRoleMarker;
    private SportViewPagerAdapter viewPagerAdapter;
    GoogleMap mygoogleMap;
    MapFragment fragmentgoogle;//Google地图控件
    boolean IsMapRead=false;//地图是否加载完成
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        fragmentgoogle= (MapFragment) this.getFragmentManager().findFragmentById(R.id.qixinggoogle_mapwo); /*** google地图控件*/
        ButterKnife.bind(this);
        map.onCreate(savedInstanceState);
        long id = getIntent().getLongExtra("id", 0);
        pathRecord = PathRecordDaoManager.getPathRecord(id);
        tvHistoryType.setText(pathRecord.getType());
        initData();
        initView();

    }

    List<Float> heart = new ArrayList<>();
    List<Float> speed = new ArrayList<>();

    private void initData() {

        //generateValues();

    }

//    private void setUpMap() {
//        mAMap.setLocationSource(this);// 设置定位监听
//        mAMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
//        mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
//        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
//        mAMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
//    }

    private void initView() {

        Mylocation aMapLocation=new Mylocation();
        if(null!=MyApplication.aMapLocation&&0.0!=MyApplication.aMapLocation.getLatitude()){
            aMapLocation.setmAltitude(MyApplication.aMapLocation.getAltitude());
            aMapLocation.setmLongitude(MyApplication.aMapLocation.getLongitude());
        }else if(null!=Util.getNetWorkLocation(this)){
            aMapLocation.setmAltitude(Util.gps84_To_Gcj02(Util.getNetWorkLocation(this).getAltitude(),Util.getNetWorkLocation(this).getLongitude()).getWgLat());
            aMapLocation.setmLongitude(Util.gps84_To_Gcj02(Util.getNetWorkLocation(this).getAltitude(),Util.getNetWorkLocation(this).getLongitude()).getWgLon());
        }

            if(Util.outOfChina(aMapLocation.getmAltitude(),aMapLocation.getmLongitude())){
                if (mAMap == null) {
                    mAMap = map.getMap();
                    mAMap.setOnMapLoadedListener(this);
                    //setUpMap();
                }
                map.setVisibility(View.VISIBLE);
                fragmentgoogle.getView().setSystemUiVisibility(View.GONE);
            }else{
                map.setVisibility(View.GONE);
                fragmentgoogle.getView().setSystemUiVisibility(View.VISIBLE);
                fragmentgoogle.getMapAsync(this);//Google地图初始化
            }


        if (mAMap == null) {
            mAMap = map.getMap();
            mAMap.setOnMapLoadedListener(this);
            //setUpMap();
        }
        viewPagerAdapter = new SportViewPagerAdapter(getSupportFragmentManager(),
                pathRecord.getSpeedListString(),pathRecord.getHeartListString());
        viewPagerHistory.setAdapter(viewPagerAdapter);
        viewPagerHistory.setCurrentItem(0);
        viewPagerHistory.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    rgHistory.check(R.id.rb_history_0);
                } else {
                    rgHistory.check(R.id.rb_history_1);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        GridLayoutManager manager = new GridLayoutManager(this, 2);
        HistoryDetailAdapter sportHistoryAdapter = new HistoryDetailAdapter(pathRecord);
        recyclerViewHistoryDetail.setAdapter(sportHistoryAdapter);
        recyclerViewHistoryDetail.setLayoutManager(manager);

    }

    private List<Float> string2List(String data) {
        List<Float> list = new ArrayList<>();
        if (TextUtils.isEmpty(data)) return list;
        String[] datas = data.split(",");
        for (String value : datas) {
            list.add(Float.valueOf(value));
        }
        return list;
    }

    private void generateValues() {
        String heartListString = pathRecord.getHeartListString();
        Log.i(TAG, "generateValues: "+heartListString);
        String speedListString = pathRecord.getSpeedListString();
        Log.i(TAG, "generateValues: "+speedListString);
        heart = string2List(heartListString);
        speed = string2List(speedListString);
//        for (int i = 0; i < maxNumberOfLines; ++i) {
//            for (int j = 0; j < numberOfPoints; ++j) {
//                randomNumbersTab[i][j] = (float) Math.random() * 50f + 5;
//            }
//        }
    }


    @OnClick(R.id.bt_signin_back)
    public void onViewClicked() {
        finish();
    }


    private static final String TAG = "HistoryActivity";


    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
                    setupRecord();
                    break;
                default:
                    break;
            }
        }

    };

    private void setupRecord() {
        // 轨迹纠偏初始化

        if (pathRecord != null) {
            String pathLines = pathRecord.getPathline();
            List<AMapLocation> recordList = Util.parseLocations(pathLines);
            String mStart = pathRecord.getStratpoint();
            String mEnd = pathRecord.getEndpoint();
            AMapLocation startLoc = Util.parseLocation(mStart);
            AMapLocation endLoc = Util.parseLocation(mEnd);
            if (recordList == null || startLoc == null || endLoc == null) {
                return;
            }
            LatLng startLatLng = new LatLng(startLoc.getLatitude(),
                    startLoc.getLongitude());
            LatLng endLatLng = new LatLng(endLoc.getLatitude(),
                    endLoc.getLongitude());
            mOriginLatLngList = Util.parseLatLngList(recordList);
            addOriginTrace(startLatLng, endLatLng, mOriginLatLngList);

        } else {
        }

    }

    private void addOriginTrace(LatLng startPoint, LatLng endPoint,
                               final List<LatLng> originList) {

        mOriginStartMarker = mAMap.addMarker(new MarkerOptions().position(
                startPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.start)));
        //jumpPoint(mOriginStartMarker);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mOriginPolyline = mAMap.addPolyline(new PolylineOptions().color(
                        Color.BLUE).addAll(originList).setCustomTexture
                        (BitmapDescriptorFactory.fromResource(R.drawable.mapline)));
                mOriginPolyline.setWidth(14f);

            }
        },20);




        mOriginEndMarker = mAMap.addMarker(new MarkerOptions().position(
                endPoint).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.end)));
      //  jumpPoint(mOriginEndMarker);
        try {
            mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(),
                    50));
        } catch (Exception e) {
            e.printStackTrace();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(IsMapRead){
                    startGrowAnimation(mOriginStartMarker,300L);
                    startGrowAnimation(mOriginEndMarker,600L);
                }
            }
        },1000);
//        mOriginRoleMarker = mAMap.addMarker(new MarkerOptions().position(
//                startPoint).icon(
//                BitmapDescriptorFactory.fromBitmap(BitmapFactory
//                        .decodeResource(getResources(), R.drawable.walk))));
    }

    private LatLngBounds getBounds() {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (mOriginLatLngList == null) {
            return b.build();
        }
        for (int i = 0; i < mOriginLatLngList.size(); i++) {
            b.include(mOriginLatLngList.get(i));
        }
        return b.build();

    }

    private final static int AMAP_LOADED = 2;

    @Override
    public void onMapLoaded() {
        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
        IsMapRead=true;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mygoogleMap=googleMap;



        String pathLines = pathRecord.getPathline();
        List<AMapLocation> recordList = Util.parseLocations(pathLines);
        com.google.android.gms.maps.model.LatLng sydney = new com.google.android.gms.maps.model.LatLng(recordList.get(0).getLatitude(), recordList.get(0).getLongitude());
        mygoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdateFactory.newLatLngZoom(sydney, 16));
        List<com.google.android.gms.maps.model.LatLng> mPolyoptionsLatLng=new ArrayList<>();
        for(int i=0;i<recordList.size();i++){
            mPolyoptionsLatLng.add(new com.google.android.gms.maps.model.LatLng(recordList.get(i).getLatitude(),recordList.get(i).getLongitude()));
        }
        for(int i=0;i<mPolyoptionsLatLng.size()-1;i++){
            mygoogleMap.addPolyline(new com.google.android.gms.maps.model.PolylineOptions().add(mPolyoptionsLatLng.get(i),mPolyoptionsLatLng.get(i+1)).width(10)
                    .color(Color.BLUE).geodesic(true));
        }
      final   com.google.android.gms.maps.model.MarkerOptions markerOption2 = new com.google.android.gms.maps.model.MarkerOptions();
        markerOption2.position(new com.google.android.gms.maps.model.LatLng(recordList.get(0).getLatitude(), recordList.get(0).getLongitude()));
        markerOption2.draggable(true);
        markerOption2.icon(com.google.android.gms.maps.model.BitmapDescriptorFactory.fromResource(R.drawable.qidian));
         mygoogleMap.addMarker(markerOption2);

        final  com.google.android.gms.maps.model.MarkerOptions markerOption3 = new com.google.android.gms.maps.model.MarkerOptions();
        markerOption3.position(new com.google.android.gms.maps.model.LatLng(recordList.get(recordList.size()-1).getLatitude(), recordList.get(recordList.size()-1).getLongitude()));
        markerOption3.draggable(true);
        markerOption3.icon(com.google.android.gms.maps.model.BitmapDescriptorFactory.fromResource(R.drawable.zhongdian));
        mygoogleMap.addMarker(markerOption3);

    }

    public void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mAMap.getProjection();
        final LatLng markerLatlng = marker.getPosition();
        Point markerPoint = proj.toScreenLocation(markerLatlng);
        markerPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(markerPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * markerLatlng.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * markerLatlng.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }





    /**
     * 地上生长得Marker
     *
     * @param marker Marker
     */
     private void startGrowAnimation(Marker marker,Long time) {
                 if (marker != null) {
                         Animation animation = new ScaleAnimation(0, 1, 0, 1);
                         animation.setInterpolator(new LinearInterpolator());
                         // 整个移动所需要的时间
                         animation.setDuration(time);
                         // 设置动画
                         marker.setAnimation(animation);
                         // 开始动画
                         marker.startAnimation();
                     }
             }
}
